<template>
  <div class="bindAccount">
    <section>
      <el-row class="preson-email">
        <el-col :span="20">
          <div class="email box">
            <i class="ipng icon_yiouxiang"></i>
            <div class="tips">
              <p class="p1">
                <span>邮箱</span>
                <strong>{{userInfo.email==""?'未绑定':userInfo.email}}</strong>
              </p>
              <p class="p2">
                可用邮箱找回密码
              </p>
            </div>
          </div>
        </el-col>
        <el-col :span="4" class="clear" v-if="EmailFlag==1">
          <el-button v-show="userInfo.email!=''" type="text" @click="Untying(0)">解绑</el-button>
          <el-button v-show="userInfo.email!=''" class="roundBtn fr" type="primary" round @click="bindAccount(0)">更改</el-button>
          <el-button v-show="userInfo.email==''" class="roundBtn fr" type="primary" round @click="bindAccount(0)">绑定</el-button>
        </el-col>
        <el-col class="not-opened" :span="4" v-else>
          管理员暂未开放邮箱功能，无法绑定
        </el-col>
      </el-row>
      <el-row class="preson-phone">
        <el-col :span="20">
          <div class="phone box">
            <i class="ipng icon_shouji"></i>
            <div class="tips">
              <p class="p1">
                <span>手机</span>
                <strong>{{userInfo.telphone==""?'未绑定':userInfo.telphone}}</strong>
              </p>
              <p class="p2">
                可用手机号加密码登录网站，可用手机号找回密码
              </p>
            </div>
          </div>
        </el-col>
        <el-col :span="4" class="clear" v-if="phoneFlag==1">
          <el-button v-show="userInfo.telphone!=''" type="text" @click="Untying(1)">解绑</el-button>
          <el-button v-show="userInfo.telphone!=''" class="roundBtn fr" type="primary" round @click="bindAccount(1)">更改</el-button>
          <el-button v-show="userInfo.telphone==''" class="roundBtn fr" type="primary" round @click="bindAccount(1)">绑定</el-button>
        </el-col>
        <el-col class="not-opened" :span="4" v-else>
          管理员暂未开放短信功能，无法绑定
        </el-col>
      </el-row>
    </section>

    <el-dialog class="emailDialog accountDialog" :title="fType==0?'绑定邮箱':'绑定手机'" width="500px" :visible.sync="dialogVisible" @close="closeDialog">
      <el-form :model="accountForm" :rules="rules" ref="accountForm" label-width="90px" label-position="left">
        <template v-if="fType==0">
          <el-form-item label="邮箱地址" prop="email">
            <el-input v-model.trim="accountForm.email" placeholder="请输入你的邮箱" :disabled="btnDisabled==true&&disabledNum==0"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="eCode">
            <el-input class="codeInput" v-model.number="accountForm.eCode" placeholder="请输入验证码"></el-input>
            <el-button class="getCodeBtn" type="primary" :disabled="btnDisabled==true&&disabledNum==0" @click="getCode('email',accountForm.email)" v-html="eCodeTipsWord" v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="发送信息中，请勿刷新" element-loading-background="rgba(0, 0, 0, .8)"></el-button>
          </el-form-item>
        </template>
        <template v-if="fType==1">
          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input v-model.number="accountForm.phoneNumber" placeholder="请输入您的手机号码" :disabled="btnDisabled==true&&disabledNum==1"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="pCode">
            <el-input class="codeInput" v-model.number="accountForm.pCode" placeholder="请输入验证码"></el-input>
            <el-button class="getCodeBtn" type="primary" :disabled="btnDisabled==true&&disabledNum==1" @click="getCode('phoneNumber',accountForm.phoneNumber)" v-html="pCodeTipsWord" v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="发送信息中，请勿刷新" element-loading-background="rgba(0, 0, 0, .8)"></el-button>
          </el-form-item>
        </template>
        <el-form-item class="submit-item">
          <el-button type="primary" @click="submitForm('accountForm')">确定</el-button>
         <el-button  @click='resetForm("accountForm")'>取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      fullscreenLoading: false,
      userInfo: "",
      dialogVisible: false,
      fType: 0,
      accountForm: {
        email: null,
        phoneNumber: null,
        eCode: null,
        pCode: null,
      },
      eCodeTipsWord: "获取验证码",
      pCodeTipsWord: "获取验证码",
      btnDisabled: false,
      disabledNum: null,//点击获取验证码之后，禁止对应的输入框输入
      rules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur'] }
        ],
        phoneNumber: [
          { type: 'number', required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        eCode: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ],
        pCode: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ],
      },
      //发短信是否被禁止，1为不禁止，2为禁止
      phoneFlag: 1,
      EmailFlag: 1,
       timer: null,
    }
  },
  created() {
  },
  mounted() {
    this.clearUserInfo();
    this.getinfo();
    this.checkPhoneForbid();
    this.checkEmailForbid();
  },
  methods: {
    // 管理后台开放短信功能，前台才能短信发二维码
    // 手机：判断后台是否开放短信功能
    checkPhoneForbid() {
      let success = res => {
        this.phoneFlag = res.data.flag;
      };
      this.$ajax({
        url: "api/system/sms_config",
        method: "get",
        params: {

        },
        func: { success: success }
      });
    },
    // 邮箱：判断后台是否开放短信功能
    checkEmailForbid() {
      let success = res => {
        this.EmailFlag = res.data.flag;
      };
      this.$ajax({
        url: "api/system/email_config",
        method: "get",
        params: {

        },
        func: { success: success }
      });
    },
    // 关闭弹窗
    closeDialog() {
      this.$refs.accountForm.clearValidate(); //移除校验结果
    },
      // 优化，后台修改了手机邮箱信息，此处页面刷新的时候，请求一下再更新信息
        clearUserInfo() {
      let success = res => {
      };
      this.$ajax({
        url: "api/login/new_login",
        method: "put",
        data: {

        },
        func: { success: success }
      });
    },
    // 获取用户信息
    getinfo() {
      let success = res => {
        this.userInfo = res.data.userinfo;
      };
      this.$ajax({
        url: "api/login/new_login",
        method: "get",
        params: {

        },
        func: { success: success }
      });
    },
    // 绑定邮箱/手机：
    bindAccount(type) {
      this.fType = type;
      this.dialogVisible = true;
    },
    // 获取验证码
    getCode(_type, _code) {
      this.$refs.accountForm.validateField(_type, (error) => {
        if (!error) {
          this.fullscreenLoading = true;
          let success = res => {
            this.$message.success(res.msg);
            this.getTime();
            this.fullscreenLoading = false;
          };
          let fail = res => {
            this.$message.warning(res.msg);
            this.fullscreenLoading = false;
          };
          let timeout = res => {
            this.$message.warning(res.msg);
            this.fullscreenLoading = false;
          }
          this.$ajax({
            url: "api/login/send_phone_mail",
            method: "get",
            params: {
              phone: _code,
              ismailphone: this.fType
            },
            func: { success: success, fail: fail, timeout: timeout }
          });
        }
      });
    },
    getTime() {
      let success = res => {
        if (res.status == "success") {
          if (res.data != "") {
            let timeCount = res.data['next_time'];
            if (this.fType == 0) {
              this.disabledNum = 0;
              this.setIntervalTime(timeCount, 0);
            } else {
              this.disabledNum = 1;
              this.setIntervalTime(timeCount, 1);
            }
          }
        }
      };
      this.$ajax({
        url: "api/login/get_next_time",
        method: "get",
        params: {
          ismailphone: this.fType,
        },
        func: { success: success }
      });
    },
    //设置倒计时提示：
    setIntervalTime(timeCount, type) {
      this.timer= setInterval(() => {
        this.btnDisabled = true;
        timeCount--;
        if (type == 0) {
          this.eCodeTipsWord = "重新发送(" + timeCount + ")";
        } else {
          this.pCodeTipsWord = "重新发送(" + timeCount + ")";
        }
        if (timeCount == 0) {
          clearInterval( this.timer);
          this.btnDisabled = false;
          if (type == 0) {
            this.eCodeTipsWord = "获取验证码";
          } else {
            this.pCodeTipsWord = "获取验证码";
          }
        }
      }, 1000);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          this.sendInfo();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName){
        this.fType == 1 ?  this.disabledNum = 1 : this.disabledNum = 0
        this.eCodeTipsWord =  this.pCodeTipsWord = "获取验证码";
        this.btnDisabled = false;
        this.dialogVisible = false
        clearInterval(this.timer);
        this.$refs[formName].resetFields();
    },
    sendInfo() {
      let success = res => {
        this.eCodeTipsWord =  this.pCodeTipsWord = "获取验证码";
        this.btnDisabled = false;
        this.dialogVisible = false;
        clearInterval(this.timer);
        this.$refs.accountForm.resetFields();
         this.fType == 1 ?  this.disabledNum = 1 : this.disabledNum = 0

        this.$message.success("绑定成功")
        this.getinfo();
      };

      let fail = (res=>{

          this.$message.error(res.msg+'')
          this.eCodeTipsWord =  this.pCodeTipsWord = "获取验证码";
          this.btnDisabled = false;
          // clearInterval(this.timer);
          // this.$refs.accountForm.resetFields();
           this.fType == 1 ?  this.disabledNum = 0 : this.disabledNum =1
      })


      this.$ajax({
        url: "api/login/check_phone_email",
        method: "put",
        data: {
          ismailphone: this.fType,
          code: this.fType == 0 ? this.accountForm.eCode : this.accountForm.pCode,
          do_what: 0,
          mailPhone: this.fType == 0 ? this.accountForm.email : this.accountForm.phoneNumber
        },
        func: { success: success, fail: fail }
      });
    },
    // 解绑：参数（邮箱0，手机1）
    Untying(ismailphone) {
      this.$confirm('您确定要解绑吗？', '解绑', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'removeing'
      }).then(() => {
        let success = res => {
          this.$message.success("解绑成功");
          this.getinfo();
        };
        this.$ajax({
          url: "api/login/delete_emailphone",
          method: "delete",
          params: {
            ismailphone: ismailphone,
          },
          func: { success: success }
        });
      }).catch(() => { });
    },


  }
}
</script>

